package com.example.demo.service.impl;

import com.example.demo.entity.Banner;
import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ErrorCode;
import com.example.demo.mapper.BannerMapper;
import com.example.demo.service.BannerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class BannerServiceImpl implements BannerService {

    private static final Logger logger = LoggerFactory.getLogger(BannerServiceImpl.class);

    @Autowired
    private BannerMapper bannerMapper;

    /**
     * 添加或更新商品的轮播图
     * 此方法首先检查传入的商品ID和轮播图列表是否有效，然后比较数据库中已有的轮播图和新提供的列表，
     * 删除数据库中不再存在的轮播图，并添加新列表中不存在于数据库的轮播图
     * 
     * @param goodsId 商品ID，用于标识轮播图所属的商品
     * @param banners 轮播图URL列表，代表需要添加或更新的轮播图
     * @return 返回新添加的轮播图列表
     * @throws BusinessException 当商品ID或轮播图列表无效时抛出业务异常
     */
    @Override
    @Transactional
    public List<Banner> addBanners(Integer goodsId, List<String> banners) {
        // 检查参数有效性
        if (goodsId == null || banners == null || banners.isEmpty()) {
            logger.error("参数错误: goodsId={}, banners={}", goodsId, banners);
            throw new BusinessException(ErrorCode.INVALID_PARAMETER);
        }

        // 查询数据库中已有的banners
        List<Banner> dbBanners = bannerMapper.selectBannersByGoodsId(goodsId);
        Set<String> dbUrls = dbBanners.stream()
            .map(Banner::getUrl)
            .collect(Collectors.toSet());
        
        // 用于高效查找的新轮播图集合
        Set<String> newUrls = new HashSet<>(banners);

        // 删除数据库中存在但新列表中没有的banners
        dbBanners.stream()
            .filter(banner -> !newUrls.contains(banner.getUrl()))
            .forEach(banner -> bannerMapper.deleteBannerById(banner.getId()));

        // 新增新列表中存在但数据库中没有的banners
        List<Banner> addedBanners = banners.stream()
            .filter(url -> !dbUrls.contains(url))
            .map(url -> {
                Banner banner = new Banner();
                banner.setGoods_id(goodsId);
                banner.setUrl(url);
                banner.setCreate_time(new Date());
                banner.setUpdate_time(new Date());
                bannerMapper.insertBanner(banner);
                return banner;
            }).collect(Collectors.toList());

        // 日志记录成功同步信息
        logger.info("成功同步轮播图: goodsId={}, banners={}", goodsId, banners);
        return addedBanners;
    }

    @Override
    public List<Banner> getBannersByGoodsId(Integer goodsId) {
        if (goodsId == null) {
            logger.error("参数错误: goodsId={}", goodsId);
            throw new BusinessException(ErrorCode.INVALID_PARAMETER);
        }

        List<Banner> banners = bannerMapper.selectBannersByGoodsId(goodsId);
        logger.info("成功查询轮播图: goodsId={}, banners={}", goodsId, banners);
        return banners;
    }

    @Override
    public boolean deleteBannerById(Integer id) {
        if (id == null) {
            logger.error("参数错误: id={}", id);
            throw new BusinessException(ErrorCode.INVALID_PARAMETER);
        }

        int result = bannerMapper.deleteBannerById(id);
        if (result > 0) {
            logger.info("成功删除轮播图: id={}", id);
            return true;
        } else {
            logger.error("删除轮播图失败: id={}", id);
            throw new BusinessException(ErrorCode.BANNERS_ADD_ERROR);
        }
    }
}
